package org.dreamwork.cai.spring;

import org.dreamwork.cai.io.IRemoteServiceProvider;
import org.dreamwork.cai.io.IRouteBroadcaster;
import org.dreamwork.cai.jmx.CrossApplicationInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component
public class SpringServiceManagerBridge {
    private final Logger logger = LoggerFactory.getLogger (SpringServiceManagerBridge.class);

    private ConfigurableListableBeanFactory factory;
    private CrossApplicationInvocation cai;

    public void setCrossApplicationInvocation (CrossApplicationInvocation cai) {
        this.cai = cai;
    }

    @Autowired
    public void setBeanFactory (ConfigurableListableBeanFactory factory) {
        this.factory = factory;
    }

    @PreDestroy
    public void doDestroy () {
        try {
            if (logger.isTraceEnabled ()) {
                logger.trace ("try unbinding service provider ...");
            }
            IRemoteServiceProvider provider = factory.getBean (IRemoteServiceProvider.class);
            provider.unbind ();
            logger.info ("service provider unbound.");
        } catch (Exception ex) {
            if (logger.isTraceEnabled ()) {
                logger.warn (ex.getMessage (), ex);
            }
        }

        try {
            if (logger.isTraceEnabled ()) {
                logger.trace ("try unbinding route broadcaster ...");
            }
            IRouteBroadcaster rb = factory.getBean (IRouteBroadcaster.class);
            rb.unbind ();
            logger.info ("route broadcaster unbound ...");
        } catch (Exception ex) {
            if (logger.isTraceEnabled ()) {
                logger.warn (ex.getMessage (), ex);
            }
        }

        try {
            if (logger.isTraceEnabled ()) {
                logger.trace ("try shutting down local broadcaster ...");
            }
            SpringLocalBroadcastBridge lbs = factory.getBean (SpringLocalBroadcastBridge.class);
            lbs.shutdown ();
            logger.info ("local broadcaster shutdown complete");
        } catch (Exception ex) {
            if (logger.isTraceEnabled ()) {
                logger.warn (ex.getMessage (), ex);
            }
        }

        try {
            if (logger.isTraceEnabled ()) {
                logger.trace ("try unregister jmx mBean");
            }
            if (cai != null) {
                cai.dispose ();
            }
        } catch (Exception ex) {
            if (logger.isTraceEnabled ()) {
                logger.warn (ex.getMessage (), ex);
            }
        }
    }
}